package com.xm.xmds1705083.service.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Company 杭州新苗网络科技有限公司
 * @Author : loysen
 * @DateTime：2017年10月13日 下午5:40:30
 *
 * @Description : {自定义应用层心跳包实现}
 */
public class MyIdleHandler extends ChannelHandlerAdapter {

	Logger logger = LoggerFactory.getLogger(MyIdleHandler.class);

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		System.out.println("-- 服务端心跳 --");
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent e = (IdleStateEvent) evt;
			if (e.state() == IdleState.READER_IDLE) {
				ctx.close();
				System.out.println("READER_IDLE 读超时");
				logger.info("READER_IDLE 读超时");
			} else if (e.state() == IdleState.WRITER_IDLE) {
				ByteBuf buff = ctx.alloc().buffer();
				buff.writeBytes("idle test".getBytes());
				ctx.writeAndFlush(buff);
				System.out.println("WRITER_IDLE 写超时");
				logger.info("WRITER_IDLE 写超时");
			}else if(e.state()== IdleState.ALL_IDLE){
				logger.info("ALL_IDLE 超时");
				System.out.println("ALL_IDLE  超时");
			}
		}
	}
}

